package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.common.config.minio.properties.AppMinioProperties;
import com.atguigu.gmall.product.service.FileUploadService;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

/**
 * @author lfy
 * @Description
 * @create 2022-10-31 15:40
 */
@Data
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    AppMinioProperties minioProperties;
    @Autowired
    MinioClient minioClient;

    @Override
    public String uploadToMinio(MultipartFile file) throws Exception {

        //1）抽取到配置文件中，让代码读取配置文件的值
        //2）如何让任何代码直接可以 @Autowired的方式拿到MinioClient 而不是自己new

        //1、创建出MinioClient


        //2、判断桶是否存在
        if(!minioClient.bucketExists(minioProperties.getBucket())){
            minioClient.makeBucket(minioProperties.getBucket());
        }

        //3、上传文件
//        file 2020-10-15
        String date = DateUtil.formatDate(new Date());

        String objectName = date+"/"+UUID.randomUUID().toString().replace("-","")
                +  "_"
                + file.getOriginalFilename();
        InputStream inputStream = file.getInputStream();

        //参数
        PutObjectOptions options = new PutObjectOptions(inputStream.available(),-1L);
        options.setContentType(file.getContentType());

        minioClient.putObject(minioProperties.getBucket(),objectName,inputStream,options);


        //4、返回文件的访问地址
        String url = minioProperties.getEndpoint()+"/"+minioProperties.getBucket()+"/"+objectName;


        return url;
    }
}
